package logic

import (
	"context"
	"fmt"
	"models"
	"time"

	"vip_srv/internal/svc"
	"vip_srv/vip_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *vip_srv.UpdateRequest) (*vip_srv.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	var order models.Order
	if err := models.DB.Where("snow = ?", in.Snow).Limit(1).Find(&order).Error; err != nil {
		return nil, err
	}
	if in.Status == "TRADE_SUCCESS" {
		order.Status = "交易完成"
		uinx, _ := models.RDB.Get(models.Ctx, fmt.Sprintf("vip_%d", order.UserId)).Int64()
		if uinx < time.Now().Unix() {
			MonthAdd := time.Now().AddDate(0, int(order.AskMonth), 0)
			models.RDB.Set(models.Ctx, fmt.Sprintf("vip_%d", order.UserId), MonthAdd.Unix(), 0)
		} else {
			now := time.Unix(uinx, 0)
			date := now.AddDate(0, int(order.AskMonth), 0)
			models.RDB.Set(models.Ctx, fmt.Sprintf("vip_%d", order.UserId), date.Unix(), 0)
		}
	} else {
		return nil, fmt.Errorf("交易失败，钱款已退回")
	}
	if err := models.DB.Create(&order).Error; err != nil {
		return nil, err
	}
	return &vip_srv.UpdateResponse{}, nil
}
